#include "../../LIB/prpsock/prpsock.h"
#include "dbwrappers.h"
#include "userinfo.h"
#include "hash.h"

class MyLoginManager : public BAM::cLoginManager
{
private:
	DatabaseManager<UserInfo> *dbm;
	bool inited;
	UserInfo *ui;
	int id;

public:
        MyLoginManager()
        {
			ui = NULL;
			id = 0;

			dbm = 0;

			inited = false;
			try
			{
				dbm = new DatabaseManager<UserInfo>("users.db", false);
			}

			catch (const DbException &e)
			{
				throw BAM::EXC_Login;
			}
			catch (const cException &e)
			{
				throw BAM::EXC_Login;
			}
			inited = true;
        }

        BAM::cPacket getPassword(const BAM::cPacket &login)
        {
			BAM::cPacket p = login;
			if (!inited) throw BAM::EXC_Login;

			p.insertTail((const BAM::byte*)"", 1);
			char *username = (char*)p.getData();

			char *buf =  (char*)dbm->GetRawData(username);
			if (NULL != buf)
			{
				ui = new UserInfo(buf);
				//free(buf);
				buf = 0;
			}
			else 
				throw BAM::EXC_Login; //no such username

			return BAM::cPacket((BAM::byte*)ui->password, strlen(ui->password));
			
			
        }

		int GetId()
		{
			if (NULL == ui) return 0;
			
			return atoi(ui->id);
		}

		bool AddRawRecord(void * key, int keylength, void *buf, int buflength)
		{
			return dbm->AddRawRecord(key, keylength, buf, buflength);
		}

		~MyLoginManager()
		{
			if (ui)
				delete ui;
			//if (dbm)
				delete dbm;
		}
};
